import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, ValidationErrors, ValidatorFn, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import {  ActionSheetConfig } from 'ngx-weui';
import { ApiService } from 'src/app/core/api';
import { Global } from 'src/app/core/global';
import { StorageService } from 'src/app/core/sotrage/storage.service';
import { GB } from '../../../environments/environment';
import { I18nService } from '../../core/i18n/i18n.service';

@Component({
	templateUrl: './index.component.html',
	styleUrls: ['./index.less'],
})
export class RegisterComponent implements OnInit {
	isEmail = false;
	constructor(private i: I18nService, private router: Router, private fb: FormBuilder, private global: Global, private api: ApiService, private sto: StorageService) {
		this.i.get(['MSG.register-code', 'MSG.register-user']).subscribe(res => {
			this.msgData = res;
		});
	}
	pageType = 1;

	config: ActionSheetConfig = {
		title: 'Language changes',
	} as ActionSheetConfig;

	gb = GB;
	ob;
	res: any = {
		id: '',
		mail: '',
		mobile: '',
		vcode: '',
		password: '',
		rpassword: '',
		worldpost: '1',
	};
	registerEmailForm: FormGroup;
	registerMobileForm: FormGroup;
	passwordForm: FormGroup;
	imageVerifyCodeId: any;
	e: number;
	msgData: any;

	sendCodeType = false;
	sendCodeNum = 10;
	_timer;
	selData=[{id:'86',name:'+86'},{id:'81',name:'+81'}]

	ngOnInit() {
		this.configForm();
	}

	configForm(){
			this.registerEmailForm = this.fb.group(
				{
					email: ['', [Validators.required, Validators.pattern("^(([0-9a-zA-Z]+)|([0-9a-zA-Z]+[_.0-9a-zA-Z-]*[0-9a-zA-Z-]+))@([a-zA-Z0-9-]+[.])+([a-zA-Z]|net|NET|asia|ASIA|com|COM|gov|GOV|mil|MIL|org|ORG|edu|EDU|int|INT|cn|CN|cc|CC)$")]],
					verifyCode: ['', [Validators.required]],
					loginPw: ['', [Validators.required]],
					reLoginPw: ['', [Validators.required]],
				},
				{
					validators: confirmValidator,
				}
			);
	
			this.registerEmailForm.setErrors({
				email: false
			});

			this.registerMobileForm = this.fb.group(
				{
					mobile: ['', [Validators.required]],
					phoneId: ["86", []],
					verifyCode: ['', [Validators.required]],
					loginPw: ['', [Validators.required]],
					reLoginPw: ['', [Validators.required]],
				},
				{
					validators: confirmValidator,
				}
			);
			this.passwordForm = this.fb.group({
				loginPw: [null, [Validators.required]],
				reLoginPw: [null, [Validators.required]],
			});
	
			this.registerMobileForm.setErrors({
				email: false
			});
		// }
	}

	onChangType(bool) {
		this.isEmail = bool;
		this.configForm();
	}

	toSendCode(type) {
		let data = type == 'mobile' ?  { 
			mobile: this.registerMobileForm.value['phoneId'] + '-' + this.registerMobileForm.value['mobile'] } : { email: this.registerEmailForm.value['email'] 
		};
		// data['type'] = "reg" ;
		if (this.registerEmailForm.value['email'] || this.registerMobileForm.value['mobile']) {
			this.api.post('注册用户时发送验证码', data).then(res => {
				this.sendCodeNum = res['data']['durationTime'];
				this.api.msgSuccess(this.msgData['MSG.register-code']);
				this.sendCodeType = true;
				this._timer = setInterval(() => {
					if (this.sendCodeNum == 0) {
						this.sendCodeType = false;
						clearInterval(this._timer);
					} else {
						this.sendCodeNum--;
					}
				}, 1000);
			});
		} else {
			this.api.msgEeeor(this.msgData['register-mail-error']);
		}
	}

	onChenkId() {
		this.registerEmailForm.value['loginId']
			? this.api.post('检查登录账号是否重复', { loginId: this.registerEmailForm.value['loginId'] }).then(res => {
					res['data']['result'] === 'Y' ? this.api.msgEeeor('此账号已注册') : this.api.msgSuccess(res['message']);
			  })
			: null;
	}
	onChenkMail() {
		this.registerEmailForm.value['email']
			? this.api.post('检查邮箱是否重复', { email: this.registerEmailForm.value['email'] }).then(res => {
					res['data']['result'] === 'Y' ? this.api.msgEeeor('此邮箱已注册') : this.api.msgSuccess(res['message']);
			  })
			: null;
	}

	onSave(f) {
		const data =f.value ;
		data.verifyCode = data.verifyCode + '';
		if(!this.isEmail){
			data['username'] = data['phoneId'] + '-' + data['mobile'];
		}else{
			data['username'] = data['email']
		}
		if (data['loginPw'] == data['reLoginPw']) {
			this.api.post('注册', data).then(res => {
				let formData = '?username='+ data['username'] + '&password = ' + data['loginPw'];
				this.api.login('登录', formData,{username:data['username'],password:data['loginPw']}).then(res => {
					this.sto.set('user', res['data']);
					let token = JSON.parse(res['data']['token']);
					this.sto.set('gameToken', token['access_token']);
					this.sto.set('token', token);
					this.router.navigateByUrl('/');
				});
			});
		} else {
			this.api.msgEeeor('密码不一致');
		}
	}
}

export const confirmValidator: ValidatorFn = (control: FormGroup): ValidationErrors | null => {
	const password = control.get('loginPw');
	const newConfirmPassword = control.get('reLoginPw');
	return password.value !== newConfirmPassword.value ? { newConfirmPasswordError: true } : null;
};
